//
//  Extension.swift
//  KLMHome
//
//  Created by 朱雨 on 2024/11/22.
//

import nRFMeshProvision

extension UIView {
    
    public var height: CGFloat {
        get {
            return frame.size.height
        }
        set {
            var rect = self.frame
            rect.size.height = newValue
            self.frame = rect
        }
    }
    
    public var width: CGFloat {
        get {
            return frame.size.width
        }
        set {
            var rect = self.frame
            rect.size.width = newValue
            self.frame = rect
        }
    }
    
    public var x: CGFloat {
        get {
            return frame.origin.x
        }
        set {
            var rect = self.frame
            rect.origin.x = newValue
            self.frame = rect
        }
    }
    
    public var y: CGFloat {
        get {
            return frame.origin.y
        }
        set {
            var rect = self.frame
            rect.origin.y = newValue
            self.frame = rect
            
        }
    }
    
    var origin:CGPoint {
        get {
            return self.frame.origin
        }
        set(newValue) {
            var rect = self.frame
            rect.origin = newValue
            self.frame = rect
        }
    }
    
    var size:CGSize {
        get {
            return self.frame.size
        }
        set(newValue) {
            var rect = self.frame
            rect.size = newValue
            self.frame = rect
        }
    }
}

extension UIView {
    
    ///获取view所在的控制器
    func currentViewController() -> UIViewController? {
        //1.通过响应者链关系，取得此视图的下一个响应者
        var n = next
        while n != nil {
            //2.判断响应者对象是否是视图控制器类型
            if n is UIViewController {
                //3.转换类型后 返回
                return n as? UIViewController
            }
            n = n?.next
        }
        return nil
    }
}

extension DispatchTime: ExpressibleByIntegerLiteral {
    public init(integerLiteral value: Int) {
        self = DispatchTime.now() + .seconds(value)
    }
}

extension DispatchTime: ExpressibleByFloatLiteral {
    public init(floatLiteral value: Double) {
        self = DispatchTime.now() + .milliseconds(Int(value * 1000))
    }
}

extension NSNotification.Name {
    ///设备添加
    static let deviceAddSuccess = NSNotification.Name.init("deviceAddSuccess")
    /// 群组删除
    static let groupDeleteSuccess = NSNotification.Name.init("groupDeleteSuccess")
    /// 群组重命名
    static let groupRenameSuccess = NSNotification.Name.init("groupRenameSuccess")
    /// 群组添加
    static let groupAddSuccess = NSNotification.Name.init("groupAddSuccess")
    /// 设备从组中移除
    static let deviceRemoveFromGroup = NSNotification.Name.init("deviceRemoveFromGroup")
    /// 设备添加到群组
    static let deviceAddToGroup = NSNotification.Name.init("deviceAddToGroup")
    /// 设备名称修改
    static let deviceNameUpdate = NSNotification.Name.init("deviceNameUpdate")
    /// 设备删除成功
    static let deviceReset = NSNotification.Name.init("deviceReset")
        
    ///家庭
    static let homeAddSuccess = NSNotification.Name.init("homeAddSuccess")
    static let homeDeleteSuccess = NSNotification.Name.init("homeDeleteSuccess")
    static let dataUpdate = NSNotification.Name.init("dataUpdate")
    static let mainPageRefresh = NSNotification.Name.init("mainPageRefresh")
    static let gatewayBindAndUnBind = NSNotification.Name.init("gatewayBindAndUnBind")
    
    ///登录账号
    static let loginPageRefresh = NSNotification.Name.init("loginPageRefresh")
    
    ///个人信息变更
    static let userInfoUpdate = NSNotification.Name.init("userInfoUpdate")
    
    static let weekChange = NSNotification.Name.init("weekChange")
    
    static let SELECTDATARELAY = NSNotification.Name.init("SELECTDATARELAY")
}

extension String {
    
    /// 十六进制 -> 十进制
    /// - Returns: 十进制
    func hexadecimalToDecimal() -> String {
        let str = self.uppercased()
        var sum = 0
        for i in str.utf8 {
            // 0-9 从48开始
            sum = sum * 16 + Int(i) - 48
            // A-Z 从65开始，但有初始值10，所以应该是减去55
            if i >= 65 {
                sum -= 7
            }
        }
        return "\(sum)"
    }
    
    /// 16进制字符串转化成color
    /// - Returns: color
    func hexToColor() -> UIColor {
        
        if self.count == 12 {
            
            let HH = self.substring(to: 4)
            let SS = self[4,4]
            let BB = self.substring(from: 8)
            
            let H: Float = Float(HH.hexadecimalToDecimal())! / 360
            let S: Float = Float(SS.hexadecimalToDecimal())! / 1000
            let B: Float = Float(BB.hexadecimalToDecimal())! / 1000
            if H == 0 && S == 0 && B == 0{
                
                return .white
            }
            
            return UIColor.init(hue: CGFloat(H), saturation: CGFloat(S), brightness: CGFloat(B), alpha: 1)
        }
        return .white
    }
    
}

///防止数组越界
extension Array {
    
    subscript(safeIndex index: Int) -> Element? {
        
        if self.count > index {
            return self[index]
        }
        return nil
    }
}

extension String {
    
    /// String使用下标截取字符串
    /// string[index] 例如："abcdefg"[3] // c
    subscript (i:Int)->String{
        let startIndex = self.index(self.startIndex, offsetBy: i)
        let endIndex = self.index(startIndex, offsetBy: 1)
        return String(self[startIndex..<endIndex])
    }
    /// String使用下标截取字符串
    /// string[index..<index] 例如："abcdefg"[3..<4] // d
    subscript (r: Range<Int>) -> String {
        get {
            let startIndex = self.index(self.startIndex, offsetBy: r.lowerBound)
            let endIndex = self.index(self.startIndex, offsetBy: r.upperBound)
            return String(self[startIndex..<endIndex])
        }
    }
    /// String使用下标截取字符串
    /// string[index,length] 例如："abcdefg"[3,2] // de
    subscript (index:Int , length:Int) -> String {
        get {
            let startIndex = self.index(self.startIndex, offsetBy: index)
            let endIndex = self.index(startIndex, offsetBy: length)
            return String(self[startIndex..<endIndex])
        }
    }
    // 截取 从头到i位置
    func substring(to:Int) -> String{
        return self[0..<to]
    }
    // 截取 从i到尾部
    func substring(from:Int) -> String{
        return self[from..<self.count]
    }
}


extension Data {
    
    /// nsdata转换成16进制字符串
    /// - Returns: 16进制字符串
    func hexadecimal() -> String {
        return map { String(format: "%02x", $0) }
                    .joined(separator: "")
    }
    
    ///大小端转化
    mutating func convertToLittleEndian() -> String {
        
        var dataList: [UInt8] = []
        //倒序
        for i in self.bytes.reversed() {
            dataList.append(i)
        }
        let data = Data.init(bytes: dataList, count: dataList.count)
        return data.toHexString().uppercased()
    }
}

extension Int {
    
    /// 十进制转16进制 1个字节
    /// - Returns: 16进制字符串
    func decimalTo2Hexadecimal() -> String {
        
        return String(format: "%02X", self)
    }
    
    /// 十进制转16进制 2个字节
    /// - Returns: 16进制字符串
    func decimalTo4Hexadecimal() -> String {
        
        return String(format: "%04X", self)
    }
}

extension UInt32 {

    func hex() -> String {
        return String(format: "%08X", self)
    }
    
}

extension UIColor {
    
    /// color转化成16进制字符串 HSB
    /// - Returns: 16进制字符串
    func colorToHexString() -> String {
        
        var a: CGFloat = 1
        var H: CGFloat = 0
        var S: CGFloat = 0
        var B: CGFloat = 0
        self.getHue(&H, saturation: &S, brightness: &B, alpha: &a)
        
        let HH = lround(H * 360).decimalTo4Hexadecimal()
        let SS = lround(S * 1000).decimalTo4Hexadecimal()
        let BB = lround(B * 1000).decimalTo4Hexadecimal()
        KLMLog("H = \(H * 360), S = \(S * 1000), B = \(B * 1000)")
        return HH + SS + BB
    }
    /// color转化成16进制字符串 HS - 4个字节
    /// - Returns: 16进制字符串
    func HSToHexString() -> String {
        
        var a: CGFloat = 1
        var H: CGFloat = 0
        var S: CGFloat = 0
        var B: CGFloat = 0
        self.getHue(&H, saturation: &S, brightness: &B, alpha: &a)
        
        let HH = lround(H * 360).decimalTo4Hexadecimal()
        let SS = lround(S * 1000).decimalTo4Hexadecimal()
//        let BB = Int(B * 1000).decimalTo4Hexadecimal()
        KLMLog("H = \(H * 360), S = \(S * 1000), B = \(B * 1000)")
        return HH + SS
    }
    /// color转化成16进制字符串 HS - 3个字节
    /// - Returns: 16进制字符串
    func HSThreeToHexString() -> String {
        
        var a: CGFloat = 1
        var H: CGFloat = 0
        var S: CGFloat = 0
        var B: CGFloat = 0
        self.getHue(&H, saturation: &S, brightness: &B, alpha: &a)
        
        let HH = lround(H * 360).decimalTo4Hexadecimal()
        let SS = lround(S * 100).decimalTo2Hexadecimal()
//        let BB = Int(B * 100).decimalTo4Hexadecimal()
        KLMLog("H = \(H * 360), S = \(S * 100), B = \(B * 100)")
        return HH + SS
    }
}

extension Dictionary {
    
    func jsonPrint() -> String {
        
        var string = ""
        do {
            try string = String.init(data: JSONSerialization.data(withJSONObject: self, options: .prettyPrinted), encoding: .utf8) ?? ""
            
        } catch {
            
            print(error)
        }
        return string
    }
}
//我们通过@IBDesignable告诉Interface Builder这个类可以实时渲染到界面中，但是这个类必须是UIView或者NSView的子类。通过@IBInspectable可以定义动态属性，即可在attribute inspector面板中可视化修改属性值
extension UITextField {
    
    @IBInspectable var placeHolderColor: UIColor? {
        get {
            return self.placeHolderColor
        }
        set {
            self.attributedPlaceholder = NSAttributedString.init(string: self.placeholder ?? "", attributes: [.foregroundColor: newValue as Any])
        }
    }
}

extension UIViewController {
    
    
    /// 获取storyboard中的xib
    /// - Parameter storyName: storyboard名称
    /// - Returns: 控制器
    static func getStoryboardVc(storyName: String) -> UIViewController {
        let ss = UIStoryboard.init(name: storyName, bundle: nil)
        let vc = ss.instantiateViewController(withIdentifier: self.className)
        return vc
    }
}

public extension UITabBar {
    
    // MARK: 让图片和文字在iOS11下仍然保持上下排列
    /// 让图片和文字在iOS11下仍然保持上下排列
    override var traitCollection: UITraitCollection {
        if UIDevice.current.userInterfaceIdiom == .pad {
            if #available(iOS 17.0, *) {///适配iOS 17，不然会闪退
                self.traitOverrides.horizontalSizeClass = .compact
            } else {
                return UITraitCollection(horizontalSizeClass: .compact)
            }
        }
        return super.traitCollection
    }
}

extension UIImage {
    ///图片旋转
    func rotateImage(withAngle angle: Double) -> UIImage? {
        if angle.truncatingRemainder(dividingBy: 360) == 0 { return self }
        
        let imageRect = CGRect(origin: .zero, size: self.size)
        let radian = CGFloat(angle / 180 * M_PI)
        let rotatedTransform = CGAffineTransform.identity.rotated(by: radian)
        var rotatedRect = imageRect.applying(rotatedTransform)
        rotatedRect.origin.x = 0
        rotatedRect.origin.y = 0
        
        UIGraphicsBeginImageContext(rotatedRect.size)
        guard let context = UIGraphicsGetCurrentContext() else { return nil }
        context.translateBy(x: rotatedRect.width / 2, y: rotatedRect.height / 2)
        context.rotate(by: radian)
        context.translateBy(x: -self.size.width / 2, y: -self.size.height / 2)
        self.draw(at: .zero)
        let rotatedImage = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        return rotatedImage
    }
    ///图片上画线
    func drawLine(start: CGPoint, end: CGPoint, color: UIColor? = .black) -> UIImage? {
        
        UIGraphicsBeginImageContextWithOptions(size, false, scale)
        guard let context = UIGraphicsGetCurrentContext() else { return nil }
        
        // 将图片画到上下文中
        draw(in: CGRect(origin: .zero, size: size))
        
        // 设置线条的属性
        context.setFillColor(UIColor.clear.cgColor)
        if let color = color {
            context.setStrokeColor(color.cgColor)
            
        }
        context.setLineWidth(1.0) // 线条宽度
//        context.setLineCap(.round) // 线条端点样式
        
        // 开始画线
        context.beginPath()
        context.move(to: start)
        context.addLine(to: end)
        context.strokePath()
        
        // 从上下文中获取新的图片
        let image = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        
        return image
    }
    
    func drawArc(center: CGPoint, radius: CGFloat, color: UIColor? = .white) -> UIImage? {
        
        UIGraphicsBeginImageContextWithOptions(size, false, scale)
        guard let context = UIGraphicsGetCurrentContext() else { return nil }
        
        // 将图片画到上下文中
        draw(in: CGRect(origin: .zero, size: size))
        
        // 设置线条的属性
        context.setFillColor(UIColor.clear.cgColor)
        if let color = color {
            context.setStrokeColor(color.cgColor)
        }
        context.setLineWidth(1.0) // 线条宽度
//        context.setLineCap(.round) // 线条端点样式
        
        // 开始画线
        context.beginPath()
        context.addArc(center: center, radius: radius, startAngle: 0, endAngle: CGFloat.pi * 2, clockwise: true)
        context.strokePath()
        
        // 从上下文中获取新的图片
        let image = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        
        return image
    }
}

extension UIView {
    ///画虚线外框
    func drawLayerDashedLine(lineWidth: CGFloat = 1, lineLength: CGFloat = 5, lineSpacing: CGFloat = 5, cornerRadius: CGFloat = 8, strokeColor: UIColor = .lightGray) {
        self.layer.cornerRadius = cornerRadius
        let borderLayer =  CAShapeLayer()
        borderLayer.bounds = self.bounds
        borderLayer.position = CGPoint(x: self.bounds.midX, y: self.bounds.midY)
        borderLayer.path = UIBezierPath(roundedRect: borderLayer.bounds, cornerRadius: cornerRadius).cgPath
        borderLayer.lineWidth = lineWidth / UIScreen.main.scale
        borderLayer.lineDashPattern = [lineLength,lineSpacing] as? [NSNumber]
        borderLayer.lineDashPhase = 0.1
        borderLayer.fillColor = UIColor.clear.cgColor
        borderLayer.strokeColor = strokeColor.cgColor
        self.layer.addSublayer(borderLayer)
    }
    
    // MARK: 5.1、添加圆角
    /// 添加圆角
    /// - Parameters:
    ///   - conrners: 具体哪个圆角
    ///   - radius: 圆角的大小
    func addCorner(conrners: UIRectCorner , radius: CGFloat) {
        let maskPath = UIBezierPath(roundedRect: self.bounds, byRoundingCorners: conrners, cornerRadii: CGSize(width: radius, height: radius))
        let maskLayer = CAShapeLayer()
        maskLayer.frame = self.bounds
        maskLayer.path = maskPath.cgPath
        self.layer.mask = maskLayer
    }
}
